import { Message } from 'element-ui'
import Cookies from 'js-cookie'
import cookie from 'js-cookie'

export default function({ $axios, redirect }) {
  $axios.onRequest((config) => {
    // let userInfo = cookie.get('userInfo')
    let token = cookie.get('SRB-TOKEN')
    if(token){
      config.headers['token'] = token
    }
    // if (userInfo) {
    //   // debugger
    //   //如果userInfo值不是一个json字符串  解析时也会报错
    //   userInfo = JSON.parse(userInfo)
    //   config.headers['token'] = userInfo.token
    // }
    console.log('Making request to ' + config.url)
  })

  $axios.onRequestError((error) => {
    console.log('onRequestError', error) // for debug
  })

  $axios.onResponse((response) => {
    console.log('Reciving resposne', response)
    if (response.data.code === 0) {
      return response
    } 
    //如果后端响应状态码为-211 代表前端提交的异步请求token过期或者被篡改  删除前端缓存的token

    else if (response.data.code === -211) {
      console.log('用户校验失败')
      Message({
        message: "登录状态失效,请重新登录",
        type: 'error',
        duration: 5 * 1000,
      })
      // debugger
      // cookie.set('userInfo', '')
      //删除无效的登录信息
      cookie.set('SRB-TOKEN','')
      window.localStorage.removeItem('userInfo')
      window.location.href = '/login?msg=-211'
      //拒绝放行请求
      return Promise.reject(response)
    } 
    else {
      Message({
        message: response.data.message+"......",
        type: 'error',
        duration: 5 * 1000,
      })
      return Promise.reject(response)
    }
  })

  //通信失败
  $axios.onResponseError((error) => {
    console.log('onResponseError', error) // for debug
  })
}
